package com.list88zhu.android.sunflower.api;

import android.text.TextUtils;

import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/8
 */
public abstract class BaseConfig implements Api.Config {

    protected Api.ConfigParams params;
    public static boolean online;


    @Override
    public void build(Retrofit.Builder builder, Api.ConfigParams params) {
        this.params = params;
        online = params.isOnline;
        builder.client(getClient());
        if(!TextUtils.isEmpty(getBaseUrl())) {
            builder.baseUrl(getBaseUrl());
        }else {
            builder.baseUrl(getBaseHttpUrl());
        }
        addConverterFactory(builder);
        addCallAdapterFactory(builder);
    }

    private void addConverterFactory(Retrofit.Builder builder) {
        List<Converter.Factory> factories = getConverterFactories();
        if (factories != null) {
            for (Converter.Factory factory : factories) {
                builder.addConverterFactory(factory);
            }
        }
    }

    private void addCallAdapterFactory(Retrofit.Builder builder) {
        List<CallAdapter.Factory> factories = getCallAdapterFactories();
        if(factories != null) {
            for (CallAdapter.Factory factory : factories) {
                builder.addCallAdapterFactory(factory);
            }
        }
    }

    protected String getBaseUrl() { return null; }
    protected HttpUrl getBaseHttpUrl() { return null; }

    public abstract OkHttpClient getClient();

    public abstract List<Converter.Factory> getConverterFactories();

    public abstract List<CallAdapter.Factory> getCallAdapterFactories();

}
